<template>
  <div class="tag-div" :class="{ 'dark-bg': theme === 'dark' }">
    <div class="tag-wrapper" ref="tagWrapper">
      <div v-for="(tag, index) in tags" :key="tag.path" class="tag-item" :class="{
        'active': currentPath === tag.path,
        'bg-color-dark': theme === 'dark',
        'ellipsis': showEllipsis && index > startIndex && index < endIndex
      }" @click="handleTagClick(tag.path)">
        <span class="tag-text">{{ tag.name }}</span>
        <span v-if="!tag.fixed" class="tag-close" @click.stop="handleTagClose(tag.path)">
          ×
        </span>
      </div>
      <div v-if="showEllipsis" class="tag-ellipsis" @click="toggleEllipsisMenu">
        ...
        <div v-if="showEllipsisMenu" class="ellipsis-menu">
          <div v-for="tag in tags" :key="tag.path" :class="{ 'active': currentPath === tag.path }"
            @click="handleTagClick(tag.path)">
            {{ tag.name }}
            <span v-if="!tag.fixed" class="ellipsis-menu-close" @click.stop="handleTagClose(tag.path)">
              ×
            </span>
          </div>
        </div>
      </div>
    </div>
    <div class="tag-actions">
      <el-tooltip content="关闭所有标签" placement="bottom">
        <div class="tag-action-btn" @click="closeAllTags">
          <el-icon>
            <Close />
          </el-icon>
        </div>
      </el-tooltip>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { Close } from '@element-plus/icons-vue';
import { useLayoutStore } from '@/store/layout';

// 标签相关状态
const layoutStore = useLayoutStore();
const router = useRouter();
const route = useRoute();
const tagWrapper = ref<HTMLDivElement | null>(null);
const showEllipsis = ref(false);
const showEllipsisMenu = ref(false);
const startIndex = ref(0);
const endIndex = ref(0);
const ellipsisThreshold = 30; // 显示省略号的标签数量阈值

// 计算属性
const layoutSettings = computed(() => layoutStore.layoutSettings);
const tags = computed(() => layoutSettings.value.tags);
const currentPath = computed(() => layoutSettings.value.currentPath);
const theme = computed(() => layoutSettings.value.theme);

// 处理标签点击
const handleTagClick = (path: string) => {
  layoutStore.updateCurrentPath(path);
  router.push(path);
};

// 处理标签关闭
const handleTagClose = (path: string) => {
  // 不能关闭固定标签
  const tag = tags.value.find(t => t.path === path);
  if (tag && tag.fixed) return;

  layoutStore.removeTag(path);

  // 如果关闭的是当前激活的标签，则跳转到最后一个标签
  if (path === currentPath.value) {
    const remainingTags = tags.value;
    if (remainingTags.length > 0) {
      router.push(remainingTags[remainingTags.length - 1].path);
    }
  }
};

// 关闭所有标签
const closeAllTags = () => {
  layoutStore.closeAllTags();
};

// 切换省略号菜单显示
const toggleEllipsisMenu = () => {
  showEllipsisMenu.value = !showEllipsisMenu.value;
};

// 计算是否需要显示省略号
const updateEllipsis = () => {
  if (!tagWrapper.value) return;

  const wrapperWidth = tagWrapper.value.clientWidth;
  const tagItems = tagWrapper.value.querySelectorAll('.tag-item:not(.ellipsis)');
  let totalWidth = 0;
  const tagWidths: number[] = [];

  // 计算所有标签的宽度
  tagItems.forEach(item => {
    const width = item.clientWidth;
    tagWidths.push(width);
    totalWidth += width;
  });

  // 判断是否需要显示省略号
  if (tags.value.length > ellipsisThreshold || totalWidth > wrapperWidth) {
    showEllipsis.value = true;

    // 计算显示的标签范围
    let visibleWidth = 0;
    let visibleCount = 0;

    // 找到可以完全显示的标签数量
    for (let i = 0; i < tagWidths.length; i++) {
      if (visibleWidth + tagWidths[i] <= wrapperWidth - 40) { // 留出省略号的宽度
        visibleWidth += tagWidths[i];
        visibleCount++;
      } else {
        break;
      }
    }

    // 始终显示第一个标签（首页）和当前激活的标签
    const activeIndex = tags.value.findIndex(tag => tag.path === currentPath.value);
    startIndex.value = 0;
    endIndex.value = tagWidths.length;

    if (visibleCount < tagWidths.length) {
      if (activeIndex > visibleCount - 1) {
        startIndex.value = Math.max(0, activeIndex - visibleCount + 1);
        endIndex.value = activeIndex + 1;
      }
    }
  } else {
    showEllipsis.value = false;
  }
};

// 监听标签变化和窗口大小变化
watch(tags, () => {
  setTimeout(updateEllipsis, 0);
});

watch(currentPath, () => {
  setTimeout(updateEllipsis, 0);
});

// 监听路由变化，添加标签
watch(
  () => route.path,
  (newPath) => {
    if (newPath !== currentPath.value) {
      const routeInfo = router.getRoutes().find(route => route.path === newPath);
      if (routeInfo && !tags.value.some(tag => tag.path === newPath)) {
        layoutStore.addTag({
          name: routeInfo.meta.title || '未命名',
          path: newPath,
          fixed: newPath === '/dashboard'
        } as any);
      }
      layoutStore.updateCurrentPath(newPath);
    }
  }
);

// 初始化
onMounted(() => {
  // 确保首页标签存在
  if (!tags.value.some(tag => tag.path === '/dashboard')) {
    const dashboardRoute = router.getRoutes().find(route => route.path === '/dashboard');
    if (dashboardRoute) {
      layoutStore.addTag({
        name: dashboardRoute.meta.title || '首页',
        path: '/dashboard',
        fixed: true
      } as any);
    }
  }

  // 监听窗口大小变化
  window.addEventListener('resize', updateEllipsis);
  setTimeout(updateEllipsis, 0);
});
</script>

<style scoped lang="scss">
.tag-div {
  display: flex;
  align-items: center;
  height: $tag-height;
  overflow: visible;
  background-color: $bg-color-light;
  position: relative;

  &.dark-bg {
    background-color: $bg-color-dark;
  }


  .tag-wrapper {
    display: flex;
    align-items: center;
    flex: 1;
    overflow-x: auto;
    overflow-y: hidden;
    height: 100%;
    padding: 0 8px;

    .tag-item {
      display: flex;
      align-items: center;
      padding: 0 8px;
      margin: 0 4px;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.2s;
      height: 80%;
      white-space: nowrap;
      color: black;

      &.bg-color-dark {
        color: white;
      }


      &.active {
        color: #646cff;
        background-color: #f0f0ff;
      }

      &.ellipsis {
        display: none;
      }



      .tag-text {
        margin-right: 4px;
      }

      .tag-close {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 16px;
        height: 16px;
        border-radius: 50%;
        font-size: 12px;

        &:hover {
          background-color: rgba(0, 0, 0, 0.1);
        }
      }
    }

    .tag-ellipsis {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 30px;
      height: 24px;
      margin: 0 4px;
      border-radius: 4px;
      background-color: $bg-color;
      cursor: pointer;
      position: relative;

      &:hover {
        background-color: $hover-color;
      }

      .ellipsis-menu {
        position: absolute;
        top: 28px;
        left: 0;
        min-width: 120px;
        max-height: 300px;
        overflow-y: auto;
        background-color: white;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        z-index: 100;
        padding: 4px 0;

        >div {
          padding: 6px 16px;
          cursor: pointer;
          white-space: nowrap;

          &:hover {
            background-color: $hover-color;
          }

          &.active {
            color: $primary-color;
            font-weight: bold;
          }

          .ellipsis-menu-close {
            margin-left: 8px;
            color: #999;

            &:hover {
              color: #333;
            }
          }
        }
      }
    }
  }

  &.dark-bg {
    .tag-item.active {
      background-color: #1e204d;
    }
  }

  .tag-actions {
    display: flex;
    align-items: center;
    padding: 0 12px;
    height: 100%;
    flex-shrink: 0;
    position: absolute;
    right: 0;
    z-index: 1;

    .tag-action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 24px;
      height: 24px;
      border-radius: 4px;
      cursor: pointer;

      .el-icon {
        color: #666666;
        font-size: 16px;
      }

      &:hover {
        background-color: $hover-color;
      }
    }
  }
}
</style>